<template>
  <div class="app-container">

    <!--搜索框-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="字典名称">
        <el-input v-model="dictionaryQuery.dictName" placeholder="请输入字典名称" />
      </el-form-item>
      <el-form-item label="字典类型">
        <el-input v-model="dictionaryQuery.dictType" placeholder="请输入字典类型" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="dictionaryQuery.status" placeholder="请选择字典状态">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dictionaryQuery.createTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dictionaryQuery.endTime"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <br>
      <el-button type="default" style="background-color: rgb(132, 178, 170)" icon="el-icon-search" @click="pageQuery()">搜索</el-button>
      <el-button type="default" icon="el-icon-refresh" @click="resetData()">重置</el-button>
      <br><br>

      <!--操作数据列表-->
      <el-button type="default" style="background-color: rgb(123, 196, 255)" icon="el-icon-plus" @click="add()">新增</el-button>
      <el-button type="default" style="background-color: rgb(137, 231, 179)" icon="el-icon-edit" :disabled="single" @click="showDialogFormVisible()">修改</el-button>
      <el-button type="default" style="background-color: rgb(255, 164, 164)" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      <el-button type="default" style="background-color: rgb(255, 197, 48)" icon="el-icon-download" @click="exportData()">导出</el-button>
      <el-button type="danger" icon="el-icon-refresh" @click="clearCache()">清除缓存</el-button>
    </el-form>

    <!--数据列表-->
    <el-table
      ref="multipleTable"
      :data="dictionaries"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="50"
      />
      <el-table-column
        label="字典编号"
        align="center"
        width="100px"
      >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.dictId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="字典名称"
        align="center"
      >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.dictName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="字典类型"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope" text-align="center">
          <router-link :to="'/nested/dictionaryData?dictType='+ scope.row.dictType " class="link-type">
            <el-link type="primary">{{ scope.row.dictType }}</el-link>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.status==0">正常</span>
          <span v-if="scope.row.status==1">停用</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
      >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
      >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
      background
      :page-size="pageSize"
      layout="prev, pager, next"
      :total="total"
      @current-change="loadDictionaries"
    />

    <!--添加弹出框-->
    <el-dialog title="字典管理" :visible.sync="dialogFormVisible">
      <el-form :model="dictionary">
        <el-form-item label="字典名称" :label-width="formLabelWidth">
          <el-input v-model="dictionary.dictName" auto-complete="off" />
        </el-form-item>
        <el-form-item label="字典类型" :label-width="formLabelWidth">
          <el-input v-model="dictionary.dictType" auto-complete="off" />
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="dictionary.status" placeholder="请选择状态">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="dictionary.remark" auto-complete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDictionary()">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>

import qs from 'qs'
import axios from 'axios'

export default {
  data() {
    return {
      ids: [],
      total: 0, // 总人数
      current: 1, // 当前页
      pageSize: 10, // 每页显示人数
      dictionaryQuery: {},
      dictionaries: [],
      dictionary: {},
      multipleSelection: [],
      dialogFormVisible: false,
      formLabelWidth: '120px',
      single: false,
      dictionaryId: []

    }
  },

  created() {
    this.loadDictionaries(this.current)
  },

  methods: {
    add() {
      this.dialogFormVisible = true
      this.dictionary = {}
    },
    loadDictionaries(current) {
      axios.post('http://localhost:8080/intelligence_community/sys-dict-type/dictionaries/page?current=' + current, this.dictionaryQuery)
        .then(res => {
          // 后台数据绑定当前集合
          this.dictionaries = res.data.records
          this.current = res.data.current
          this.total = res.data.total
        })
    },
    addDictionary() {
      if (!this.dictionary.dictId) {
        // 发送post实现dictionary添加
        axios.post('http://localhost:8080/intelligence_community/sys-dict-type/dictionary',
          qs.stringify(this.dictionary))
          .then(res => {
            if (res.data == '新增成功') {
              this.dictionary = {}
              this.loadDictionaries(this.current)
            }
          })
      } else {
        // 发送put请求进行更新
        axios.put('http://localhost:8080/intelligence_community/sys-dict-type/dictionary',
          this.dictionary)
          .then(res => {
            if (res.data == '修改成功') {
              this.dictionary = {}
              this.loadDictionaries(this.current)
            }
            if (res.data == '该类型下面有数据不能删除') {
              this.$message.warning('该类型下面有数据不能删除')
            }
          })
      }
      this.dialogFormVisible = false
    },
    handleEdit(index, row) {
      this.toggleSelection()
      this.dictionary = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
    },

    handleDelete(index, row) {
      this.$messagebox.confirm('是否确定删除？').then(() => {
        if (!row) {
          axios.delete('http://localhost:8080/intelligence_community/sys-dict-type/dictionaries/' + this.ids)
            .then(res => {
              if (res.data == '删除成功') {
                this.loadDictionaries(this.current)
              }
              if (res.data == '该类型下面有数据不能删除') {
                this.$message.warning('该类型下面有数据不能删除')
              }
            })
        } else {
          axios.delete('http://localhost:8080/intelligence_community/sys-dict-type/dictionaries/' + row.dictId)
            .then(res => {
              console.log(res)
              if (res.data == '删除成功') {
                this.loadDictionaries(this.current)
              }
              if (res.data == '该类型下面有数据不能删除') {
                this.$message.warning('该类型下面有数据不能删除')
              }
            })
        }
      })
    },

    // 修改按钮弹窗
    showDialogFormVisible() {
      if (!this.dictionary.dictId) {
        this.$message({
          showClose: true,
          message: '请至少选择一条数据',
          type: 'error'
        })
      } else {
        this.dialogFormVisible = true
      }
    },

    // 批量修改禁用与修改
    handleSelectionChange(val) {
      this.ids = []
      this.dictionaryId = []
      this.single = false
      if (val.length > 1) {
        this.single = true
      }
      if (val.length == 1) {
        this.dictionary = { dictId: val[0].dictId, dictName: val[0].dictName, dictType: val[0].dictType, status: val[0].status, remark: val[0].remark, createTime: val[0].createTime }
      }
      this.multipleSelection = val
      val.forEach(valId => {
        this.dictionaryId.push(valId.dictId)
      })
      if (val.length == 0) {
        this.dictionary = {}
      }
      val.forEach(a => {
        this.ids.push(a.dictId)
      })
    },

    // 删除
    // deleteSelected(){
    // console.log(this.dictionaryId.join()!="")
    // if (this.dictionaryId.join()!=""){
    //   if(this.$messagebox.confirm("是否确定删除？")){
    //     axios.delete("http://localhost:8080/intelligence_community/sys-dict-type/dictionaries/" +this.dictionaryId.join())
    //       .then(res => {
    //         if(res.data == "删除成功"){
    //           this.loadDictionaries(this.current);
    //         }
    //       });
    //   }
    // } else {
    //   this.$message({
    //     showClose: true,
    //     message: '请至少选择一条数据',
    //     type: 'error'
    //   });
    // }
    // },

    // 查询列表数据
    pageQuery(current) {
      // console.log(JSON.stringify(this.dictionaryQuery))
      // console.log(qs.stringify(this.dictionaryQuery))
      current = this.current
      this.loadDictionaries(current)
    },

    // 重置
    resetData() {
      this.dictionaryQuery = {}
      this.pageQuery()
    },

    //  取消全选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    // 导出数据
    exportData() {
      axios({
        method: 'get',
        url: 'http://localhost:8080/intelligence_community/sys-dict-type/downloadExcel',
        responseType: 'arraybuffer'
      })
        .then(res => {
          console.log(res)
          // 使用Blob对象将后端返回的Arraybuffer格式得数据转成blob类型的数据 window.URL.createObjectURL(blob)可以把一个blob转成blobURL，用作图片显示，文件下载（不能再服务器上存储，只能在浏览器使用）
          const b = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          // 使用URL对象将blob类型的数据生成一个在线下载的链接
          const url = URL.createObjectURL(b)
          // 然后我们使用a标签进行下载
          const link = document.createElement('a')

          // 设置导出的文件名
          link.download = '字典类型'
          link.href = url
          // 点击获取文件
          link.click();

          (err) => {
            console.log(err)
          }
        })
    }
  }
}
</script>

<style scoped>

</style>
